package com.sajhasite.web;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sajhasite.authentication.UserContext;
import com.sajhasite.domain.bean.UserBean;
import com.sajhasite.domain.entity.User;
import com.sajhasite.service.IUserService;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Inject
	private IUserService userService;

	public IUserService getUserService() {
    	return userService;
    }

	public void setUserService(IUserService userService) {
    	this.userService = userService;    	
    }
	
	@RequestMapping(value="/signup.do", method=RequestMethod.GET)
	public String  newForm(Model model) {
		model.addAttribute("user", new UserBean());
	//return new ModelAndView("usersignup","command",new User());
		return "usersignup";
	}
	
	
	@RequestMapping(value="/login.do", method=RequestMethod.GET)
	public String  userLogin(Model model) {
		model.addAttribute("user", new User());
	//return new ModelAndView("usersignup","command",new User());
		return "userlogin";
	}
	
	@RequestMapping(value="/login.do", method=RequestMethod.POST)
	public String  validateLogin(@ModelAttribute("user")User user,HttpServletRequest request) {
		System.out.println(user.getEmail()+" ***** "+user.getPassword());
		UserContext userContext=this.userService.authenticateUser(user);
	//return new ModelAndView("usersignup","command",new User());
		if(userContext.isLogged()){
			request.getSession().setAttribute("user", userContext);
			return "home";
		}
			
		else
			return "userlogin";
	}
	
	@RequestMapping(value="/signup.do", method=RequestMethod.POST)
	public String signUp(@ModelAttribute("user")UserBean userBean) {
		
		if(userBean.getEmail().trim().equals(userBean.getConfirmEmail().trim()) &&
				userBean.getPassword().trim().equals(userBean.getConfirmPassword().trim())){				
			this.userService.createUser(userBean.getEmail(), userBean.getPassword(),userBean.getDisplayName());
			//return new ModelAndView("singupsuccess", "command", null);
			return "signupsuccess";
		}
		userBean.setConfirmEmail("");
		userBean.setConfirmPassword("");
		
		return "usersignup";
		
	}
	
	
}
